package main

/* 
 by zy,
 下载 SSL 证书  
 handleDownload(cfg *CLI)
*/

import (
  "os"
  "fmt"
  "net/http"
)

/*  响应样例如下
{
  "code": 200,
  "error": "",
  "cert": {
    "certid": "690870280e5e768c40e28cb3",
    "name": "www.baidu.com-20251103",
    "uid": 1382999320,
    "common_name": "www.baidu.com",
    "dnsnames": [
      "www.baidu.com"
    ],
    "create_time": 1762160680,
    "not_before": 1762154378,
    "not_after": 1769930377,
    "orderid": "",
    "product_short_name": "",
    "product_type": "",
    "cert_type": "",
    "encrypt": "ECDSA",
    "encryptParameter": "",
    "enable": true,
    "child_order_id": "",
    "state": "",
    "auto_renew": false,
    "renewable": false,
    "ca": "-----BEGIN CERTIFICATE----- ...",
    "pri": "-----BEGIN EC PRIVATE KEY----- ..."
  }
}
*/

type RespBodyDownload struct {
    Code  int    `json:"code"`
    Error string `json:"error"`
    Cert  Cert   `json:"cert"` // -> types.go
}
 
func handleDownload(cfg *CLI) {
  var err error
  // 发送请求
  resp, err := sendDownloadRequest(cfg)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to send http request: %v\n", err)
    os.Exit(ExitRequestError)
  }
  defer resp.Body.Close()

  fmt.Printf("StatusCode: %d\n", resp.StatusCode);
  
  // verbose 模式下，输出响应JSON的全文
  if cfg.Verbose {
    respBody, err := readRespBody(resp)
    if err != nil {
      fmt.Fprintf(os.Stderr, "failed to read response: %v\n", err)
      os.Exit(ExitUnmarshalError)
    }
    dumpJson(respBody)  
  }

  r, err := parseResp[RespBodyDownload](resp)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to parse response: %v\n", err)
    os.Exit(ExitUnmarshalError)
  }
 
  if resp.StatusCode == 200 {
    cfg.CertStr = r.Cert.CertStr
    cfg.KeyStr = r.Cert.KeyStr
    r.Cert.Print() // 打印证书基本信息
    err = saveCertAndKey(cfg) //保存证书和密钥，如果未指定保存路径会打印到标准输出
    if err != nil {
      fmt.Fprintf(os.Stderr, "failed to save : %v\n", err)
      os.Exit(ExitFileError)
    }
  } else {
    fmt.Printf("Code: %d\nError: %s\n", r.Code, r.Error)
    os.Exit(ExitOtherError)
  } 
}

func sendDownloadRequest(cfg *CLI) (*http.Response, error) { //GET /sslcert/<CertID>
  return sendQiNiuRequest(cfg, http.MethodGet, "/sslcert/" + cfg.CertID, "", nil)
}

